/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.myweb.tag;

import com.myweb.MyWeb;
import com.myweb.WebAction;
import com.myweb.WebRequest;
import com.myweb.WebResponse;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;

/**
 *
 * @author DTIT
 */
public class Action extends SimpleTagSupport {

    private WebAction action;
    private String result;

    public WebAction getAction() {
        return action;
    }

    public void setAction(WebAction action) {
        this.action = action;
    }

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }

    /**
     * Creates new instance of tag handler
     */
    public Action() {
        super();
    }

    @Override
    public void doTag() throws JspException {
        JspWriter out = getJspContext().getOut();
        PageContext pageContext = (PageContext) getJspContext();
        HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
        HttpServletResponse response = (HttpServletResponse) pageContext.getResponse();
        WebRequest wreq = new WebRequest(request);
        WebResponse wres = new WebResponse();
        EntityManagerFactory emf = (EntityManagerFactory) request.getAttribute(MyWeb.KEY_EM_FACTORY);
        EntityManager em = null;
        try {

            action.prepare(wreq);
            em = emf.createEntityManager();
            em = action.process(wreq, wres, em);
            pageContext.setAttribute(result, wres.getResult());
            response.setHeader("X-Message", wres.getMessage());
            JspFragment f = getJspBody();
            if (f != null) {
                f.invoke(out);
            }

        } catch (Exception ex) {
            throw new JspException(ex);
        } finally {
            if (em != null && em.isOpen()) {
                em.close();
            }
        }
    }
}
